package com.itheima.health.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.mapper.SetmealMapper;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.pojo.SetmealCheckGroup;
import com.itheima.health.service.SetmealCheckGroupService;
import com.itheima.health.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author kcs
 * @date 2021/11/27
 * @TIME:1:40
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealCheckGroupService setmealCheckGroupService;

    /**
     * 体检套餐添加功能 套餐表 + 套餐检查组关系表
     * @param setmeal
     * @param checkgroupIds
     */
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {

        //1.添加套餐
        this.save(setmeal);

        //2.添加套餐对应的检查组关系
        List<SetmealCheckGroup> setmealCheckGroups = new ArrayList<>();
        for (Integer checkgroupId : checkgroupIds) {
            SetmealCheckGroup setmealCheckGroup = new SetmealCheckGroup();
            setmealCheckGroup.setCheckGroupId(checkgroupId);
            setmealCheckGroup.setSetmealId(setmeal.getId());
            setmealCheckGroups.add(setmealCheckGroup);
        }
        setmealCheckGroupService.saveBatch(setmealCheckGroups);
    }

    /**
     * 体检套餐分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        //设置分页条件
        IPage<Setmeal> iPage = new Page<>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        //设置查询条件
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        String queryString = queryPageBean.getQueryString();
        if(queryString != null && queryString != ""){
            wrapper.like(Setmeal::getName,queryString)
                    .or()
                    .like(Setmeal::getCode,queryString)
                    .or()
                    .like(Setmeal::getHelpCode,queryString);
        }

        //查询并封装pageResult对象
        IPage<Setmeal> page = this.page(iPage, wrapper);
        PageResult pageResult = new PageResult();
        pageResult.setRows(page.getRecords());
        pageResult.setTotal(page.getTotal());
        return pageResult;
    }
}
